<?php
namespace Modules\Payment\Entities;

use Modules\Payment\Entities\PaymentRecord;

use ThrowException;
use ByteDance;
use Cache;

use Modules\Core\Helpers\HttpClient;

class ByteDancePay
{
	protected $clientName;
	protected $payType;
	protected $pay;
	protected $app;

	public function __construct($clientName, $payType)
	{
		$this->app = ByteDance::get();
		$this->pay = $this->app->payment;
		$this->payType = $payType;
		$this->clientName = $clientName;
	}

	public function __call($name, $arguments)
    {
    	return call_user_func_array(array($this->pay, $name), $arguments);
    }

	public function config($user, $order)
	{
		$money = $order->payPrice();

		if ($order->type === 'box') {
			$title = '购买盲盒';
		}
		else {
			$title = $order->title();
		}

		$number = $order->payNumber();

		$uuid = $order->uuid;
		$body = '测试商品';

		$info = [
			'out_order_no' => $number,
			'total_amount' => $money,
			'subject' => $title,
			'body' => $body,
			'valid_time' => 300,
			'cp_extra' => $uuid,
			'notify_url' => env('APP_URL') . '/payment-callback/byte-dance',
			'disable_msg' => 0,
		];

		return  $this->precreateOrder($info);

		// return $this->pay->pay($uuid, $number, $money,  $title, [
		// 	'body' => '测试商品',
		// 	'notify_url' => 'https://baidu.com/'
		// ]);
	}

	// 预创建订单
	public function precreateOrder($params)
	{
		$signData = array_values($params);
		array_push($signData, env('BYTEDANCE_MCH_KEY'));

		$params['sign'] = $this->sign($signData);
		$params['app_id'] = env('BYTEDANCE_APPID');

		$http = new HttpClient();

		$url = 'https://developer.toutiao.com/api/apps/ecpay/v1/create_order';
		$res = $http->post($url, $params, [
			'Content-Type' =>  'application/json'
		]);

		$res = json_decode($res, true);

		if (@$res['err_no'] != 0) {
			\Log::error('抖音下单失败:');
			\Log::error($res);
			ThrowException::Conflict($res['err_tips']);
		}

		return $res['data'];
	}

	// 检验回调结果
	public function checkCallbackData($data)
	{
		$signData = [
			env('BYTEDANCE_MCH_TOKEN'),
			$data['timestamp'],
			$data['nonce'],
			$data['msg']
		];

		$sign = $this->sign($signData, 'sha1');

		if ($sign !== $data['msg_signature']) {
			\Log::error('抖音支付回调签名错误');
			ThrowException::Conflict('抖音支付回调签名错误');
		}

		return true;
	}

	// 签名
	public function sign($data, $type = 'md5')
	{
		foreach ($data as $key => $value) {
			$data[$key] = trim($data[$key]);
		}
		sort($data, 2);

		if ($type === 'md5') {
			return md5(implode("&", $data));
		}
		elseif ($type === 'sha1') {
			return sha1(implode("", $data));
		}
	}

	public function refundMoney($order, $refundMoney = null, $options = []) 
	{
		// $payment = $order->payment() ?: ThrowException::Conflict('订单无支付记录');

		// \Log::error($payment);
		// exit();

		// $orderType = 'single_order';

		// $remark = @v($options['remark'], '订单退款');

		// // $paymentRecord = $order->payment();
		// $number = $order->pay_number;

		// // \Log::error($number);
		// // exit();

		// $info = [
		// 	'out_trade_no' => $number,
		// 	'out_refund_no' => time(),
		// 	'total_fee' => $order->pay_money_price,
		// 	'refund_fee' => $refundMoney,
		// 	'refund_desc' => $remark,
		// ];

		// try {
		// 	$res = $this->pay->refund($info);
		// }
		// catch(\Yansongda\Pay\Exceptions\GatewayException $e) {
		// 	\Log::error('订单: ' . $order->id . ' 退款失败:' . $e->getMessage());
		// 	ThrowException::Conflict('退款失败, 请检查退款金额是否超出总订单金额');
		// }
	}


	public function recordPayment($order, $clientName, $paySubType, $data, $options = [])
	{
		$info = [
			'trade_number' => @$data['transaction_id'],
			'out_trade_number' => @$data['out_trade_no'],
			'client_name' => $clientName,
			'pay_type' => 'wechat',
			'pay_sub_type' => @$paySubType,
			'paid_at' => @$data['time_end'],
			'money' => @$data['total_fee'] ?: $order->pay_money_price,
			'status' => 2,
			'options' => $data
		];

		if ($order->number[0] == 'U') 
			$info['union_order_id'] = $order->id;
		else
			$info['order_id'] = $order->id;

		$record = PaymentRecord::create($info);

		$record->save();
	}

	public function success()
	{
		return [
          "err_no" => 0,
          "err_tips" => "success"
        ];
	}
}
